package com.tcm.day07;

import com.tcm.day06.TreeNode;

/**
 * 路径总和
 * https://leetcode.cn/problems/path-sum/description/?envType=problem-list-v2&envId=binary-tree
 */
public class Code05_TotalPathSum {

    class TotalPathSum{
        public boolean isTarget = false;

        public boolean hasPathSum(TreeNode root, int targetSum) {
            if(root == null) return false;
            isTarget = false;
            process(root, 0, targetSum);
            return isTarget;
        }

        public void process(TreeNode node, int preSum, int targetSum) {
            if(node.left == null && node.right == null) {
                if(preSum + node.val == targetSum) {
                    isTarget = true;
                }
                return;
            }

            preSum = node.val + preSum;
            if(node.left != null) {
                process(node.left, preSum, targetSum);
            }

            if(node.right != null) {
                process(node.right, preSum, targetSum);
            }
        }
    }

}
